<?php

/**
 * This is the model class for table "tbl_inventoryact".
 *
 * The followings are the available columns in table 'tbl_inventoryact':
 * @property integer $id
 * @property string $period
 * @property string $partno
 * @property string $warehouse
 * @property string $date
 * @property string $time
 * @property string $count
 * @property string $serial
 * @property string $lot
 * @property string $type
 * @property string $description
 * @property double $qty
 * @property double $qtyout
 * @property string $vendorno
 * @property double $cost
 * @property string $debit
 * @property string $credit
 * @property string $ponum
 * @property string $finperiod
 * @property string $source
 * @property string $key
 * @property string $rdate
 * @property string $rtime
 * @property string $rcount
 * @property string $recby
 * @property string $reason
 * @property string $job
 * @property string $terms
 * @property string $partdesc
 *
 */
class Inventoryact extends CActiveRecord
{

    public $total;

    /**
     * Returns the static model of the specified AR class.
     * @return Inventoryact the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'tbl_inventoryact';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('qty, qtyout, cost', 'numerical'),
            array('period, finperiod', 'length', 'max' => 6),
            array('partno', 'length', 'max' => 50),
            array('department', 'length', 'max' => 36),
            array('dispatch', 'length', 'max' => 15),
            array('warehouse, vendorno, recby', 'length', 'max' => 4),
            array('time', 'length', 'max' => 8),
            array('count', 'length', 'max' => 3),
            array('serial', 'length', 'max' => 36),
            array('lot,  ponum, reason', 'length', 'max' => 20),
            array('type, source', 'length', 'max' => 1),
            array('debit, credit', 'length', 'max' => 10),
            array('key', 'length', 'max' => 15),
            array('job,description', 'length', 'max' => 150),
            array('terms', 'length', 'max' => 31),
            array('date, rdate, partdesc', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, period, partno, warehouse, date, time, count, serial, lot, type, description, qty, qtyout, vendorno, cost, debit, credit, ponum, finperiod, source, key, rdate, dispatch, department, recby, reason, job, terms, partdesc', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'inventoryModel'=>array(self::BELONGS_TO,'Inventory','partno'),
            );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'period' => 'Period',
            'partno' => 'Partno',
            'warehouse' => 'Warehouse',
            'date' => 'Date',
            'time' => 'Time',
            'count' => 'Count',
            'serial' => 'Serial',
            'lot' => 'Lot',
            'type' => 'Type',
            'description' => 'Description',
            'qty' => 'Qty',
            'qtyout' => 'Qtyout',
            'vendorno' => 'Vendorno',
            'cost' => 'Cost',
            'debit' => 'Debit',
            'credit' => 'Credit',
            'ponum' => 'Ponum',
            'finperiod' => 'Finperiod',
            'source' => 'Source',
            'key' => 'Key',
            'rdate' => 'Rdate',
            'recby' => 'Recby',
            'reason' => 'Reason',
            'job' => 'Job',
            'terms' => 'Terms',
            'partdesc' => 'Partdesc',
        );
    }

    /*
     * After save an invoice, it need to call this function to insert all item of that invoice to tbl_inventory_act
     */

    public static function insertFromInvoiceItem($invoice)
    {
		return;
        $inv = Invoice::model()->findByPk($invoice);

        if ($inv != NULL) {
            //delete old item in tbl_inventory_act have same source
            Yii::app()->db->createCommand()->delete('tbl_inventoryact', ' `key` =:invoice', array('invoice' => $invoice));
            //update the item to inventory act
            $itemList = Yii::app()->db->createCommand('select * from tbl_invoice_ledger where invoice=:invoice')
                ->bindValue('invoice', $invoice)->queryAll();
            if (count($itemList) > 0) {
                foreach ($itemList as $item) {
                    $type = Yii::app()->db->createCommand('select type from tbl_inventory where partno=:partno')
                        ->bindValues(array('partno' => $item['partno']))->queryScalar();

                    if ($type == 'I') {
                        $count = getIncrementNumber('tbl_inventoryact', 'count');
                        if ($inv->invoicetype == Invoice::TYPE_CREDIT_MEMO) {
                            $item['cost'] = -abs($item['cost']);
                            $item['qty'] = -abs($item['qty']);
                        }
                        $num = Yii::app()->db->createCommand()->insert('tbl_inventoryact', array(
                            'period' => DateUtil::getDefaultPeriod(),
                            'partno' => $item['partno'],
                            'warehouse' => $item['warehouse'],
                            'date' => DateUtil::getDefaultCurrentDateTime(),
                            'time' => DateUtil::getDefaultCurrentTime(),
                            'count' => str_pad($count + 1, 3, '0', STR_PAD_LEFT),
                            'serial' => $item['serial'],
                            'type' => Yii::app()->db->createCommand('select partno from tbl_inventory where partno=:partno')->bindValues(array('partno' => $item['partno']))->queryScalar(),
                            'description' => $item['description'],
                            'cost' => $item['cost'],
                            'debit' => $item['cdebit'],
                            'credit' => $item['ccredit'],
                            'ponum' => Yii::app()->db->createCommand('select ponumber from tbl_invoice where invoice=:invoice')->bindValues(array('invoice' => $invoice))->queryScalar(),
                            'finPeriod' => DateUtil::getDefaultPeriod(),
                            'source' => 'S',
                            'key' => $invoice,
                            'qty' => $item['qty']
                        ));
                    }
                }

            }
        }
    }

    protected function beforeSave()
    {
        if ($this->IsNewRecord) {
            $count = getIncrementNumber('tbl_inventoryact', 'count');
            $this->period = DateUtil::getDefaultPeriod();
            $this->finperiod = DateUtil::getDefaultPeriod();
            $this->date = DateUtil::getDefaultCurrentDateTime();
            $this->time = DateUtil::getDefaultCurrentTime();
            $this->count = str_pad( 0, 3, '0', STR_PAD_LEFT);
            // // if($this->inventoryModel!=null){
            // //     $cost = $this->inventoryModel->averagecost;
            // // }else{
            // //     $cost = 0;
            // // }
            
            // // $this->cost=0;
            // if($this->type=='O')
            //     $this->cost  = -$cost;
            // else $this->cost = $cost;

           // $this->description = 'Adjustment';
        }
        return parent::beforeSave();
    }

    public function adjust($item, $addData)
    {
        if ($item->qty > $this->getQty($item)) {
            return  $this->in($item, $addData);
        } else  {
            return    $this->out($item, $addData);
        }
    }
    public function transfer($item, $addData)
    {
        $criteria = new CDbCriteria();
        $criteria->condition = "partno ='$item->partno' and type='I' and warehouse='$item->warehouse'";
        $criteria->order = "id ASC";
        $inModels = self::model()->findAll($criteria);

        $inModel = new Inventoryact();
        $inModel->attributes = $item->attributes;
        $inModel->partdesc = $item->description;
        $inModel->reason = $addData['reason'];
        $inModel->warehouse = $addData['towarehouse'];
        $inModel->description = 'Transfer from '.Warehouse::getDescription($item->warehouse);
        $inModel->type = 'I';        
        $inModel->source ='T';
        $inModel->validate();
        $inModel->recby = Yii::app()->user->model->employeeid;
        // $inModel->save();
        $outModel = new Inventoryact();
        $outModel->attributes = $item->attributes;
        $outModel->type = 'O';
        $outModel->rdate = DateUtil::getDefaultCurrentDateTime();
        //$outModel->rtime = DateUtil::getDefaultCurrentTime();
        $outModel->partdesc = $item->description;
        $outModel->reason = $addData['reason'];
        $outModel->description ='Transfer to '.Warehouse::getDescription($addData['towarehouse']);       
        $outModel->qty = - $outModel->qty;
        $outModel->source ='T';
        $outModel->recby = Yii::app()->user->model->employeeid;
        // $outModel->save();
       
        $removeAmount = -$outModel->qty;

        $restModelAttrs = array();
        foreach ($inModels as $inModelChild) {
            if ($removeAmount) {
                /** @var $inModel Inventoryact */

                $diff = $inModelChild->qty - $inModelChild->qtyout ;

                If ($diff >=$removeAmount) {
                    $inModelChild->qtyout += $removeAmount;
                    $removeAmount =0;
                } else {
                    $inModelChild->qtyout +=$diff;
                    $removeAmount -= $diff;
                    $inModelChild->type ='X';
                }
                //$inModel->cost = 1;
                //$inModelChild->source ='A';
                $restModelAttrs['cost'] = $inModelChild->cost;
                $restModelAttrs['ponum'] = $inModelChild->ponum;
                $restModelAttrs['vendorno'] = $inModelChild->vendorno;
                $restModelAttrs['job'] = $inModelChild->job;
                $restModelAttrs['dispatch'] = $inModelChild->dispatch;
                $restModelAttrs['department'] = $inModelChild->department;
                $inModelChild->save();
            }
            if($inModelChild->qty == $inModelChild->qtyout){
                $inModelChild->type ='X';
                $inModelChild->save();
            }
        }
        $inModel->attributes = $restModelAttrs;
        $outModel->attributes = $restModelAttrs;

        $outModel->cost = -$inModel->cost;

        return $outModel->save() && $inModel->save();

    }

    public function in($item, $addData)
    {
        $criteria = new CDbCriteria();
        $criteria->condition = "partno ='$item->partno' and type='I' and warehouse='$item->warehouse'";
        $criteria->order = "id ASC";
        $inModels = self::model()->findAll($criteria);

        $inModel = new Inventoryact();
        if($inModels)
            $inModel->attributes = $inModels[0]->attributes;
        $inModel->attributes = $item->attributes;
        if($item->description)
            $inModel->partdesc = $item->description;
        else
            $inModel->partdesc =$inModels[0]->partdesc;
        $inModel->reason = $addData['reason'];
        $inModel->description = 'Adjustment';
        $inModel->type = 'I';
        $inModel->qty = $item->qty - $this->getQty($item);
        $inModel->cost =$inModels[0]->cost;
       
        $inModel->recby =Yii::app()->user->model->employeeid;
        $inModel->dispatch =$inModels[0]->dispatch;
        $inModel->job =$inModels[0]->job;
        $inModel->validate();
        $inModel->source ='A';
        if($inModel->qty!=0)
            $inModel->save();        
        return $this->getQty($item, $addData);
    }

    public function out($item, $addData)
    {
        $criteria = new CDbCriteria();
        $criteria->condition = "partno ='$item->partno' and type='I' and warehouse='$item->warehouse'";
        $criteria->order = "id ASC";
        $inModels = self::model()->findAll($criteria);

        $outModel = new Inventoryact();
        if($inModels)
            $outModel->attributes = $inModels[0]->attributes;
        $outModel->attributes = $item->attributes;
        $outModel->type = 'O';
        $outModel->rdate = DateUtil::getDefaultCurrentDateTime();
        // $outModel->rtime = DateUtil::getDefaultCurrentTime();
       
        $outModel->reason = $addData['reason'];
        $outModel->qty = $outModel->qty - $this->getQty($item);
        $outModel->description ='Adjustment';
        $outModel->qty = $item->qty - $this->getQty($item);
        $outModel->cost =-$inModels[0]->cost;
        $outModel->recby =$inModels[0]->recby;
        if($item->description)
            $outModel->partdesc = $item->description;
        else
            $outModel->partdesc =$inModels[0]->partdesc;
        $outModel->dispatch =$inModels[0]->dispatch;
        $outModel->job =$inModels[0]->job;
        $outModel->source ='A';
        $outModel->save();
        $criteria = new CDbCriteria();
        $criteria->condition = "partno ='$item->partno' and type='I' and warehouse='$item->warehouse'";
        $criteria->order = "id ASC";
        $inModels = self::model()->findAll($criteria);
        $removeAmount = -$outModel->qty;

        //die();
        foreach ($inModels as $inModel) {
            if ($removeAmount) {
                /** @var $inModel Inventoryact */

                $diff = $inModel->qty - $inModel->qtyout ;

                If ($diff >=$removeAmount) {
                    $inModel->qtyout += $removeAmount;
                            $removeAmount =0;
                } else {
                    $inModel->qtyout +=$diff;
                    $removeAmount -= $diff;
                    $inModel->type ='X';
                }                
                $inModel->save();
            }
            if($inModel->qty == $inModel->qtyout){
                $inModel->type ='X';
                $inModel->save();
            }
        }
        return $this->getQty($item);
    }



    public function getQty($item)
    {
        return Yii::app()->db
            ->createCommand(
            "SELECT sum(qty-qtyout)  FROM tbl_inventoryact
             WHERE partno = '$item->partno' and type = 'I' and warehouse = '$item->warehouse' ")->queryScalar();
    }

}
